package com.hua.nailcampus.acl.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.hua.nailcampus.acl.service.FileUploadService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @Author:chenjianhua
 * @Date:2023/6/16 16:51
 * @Version 1.8
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${aliyun.endpoint}")
    private String endpoint;

    @Value("${aliyun.keyid}")
    private String accessKeyId;

    @Value("${aliyun.keysecret}")
    private String accessKeySecret;

    @Value("${aliyun.bucketname}")
    private String bucketName;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder()
                .build(endpoint, accessKeyId, accessKeySecret);

        try {
//            上传文件输入流
            InputStream inputStream = file.getInputStream();

//            获取文件上传的名称
            String originalFilename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("/","");//3456-98ui-0877
            originalFilename = uuid+originalFilename;
//           对上传文件进行分组处理，根据当前年月日
//          originalFilename:  2023/6/17/01.jpg
//          originalFilename:  2023/10/10
            String currentDateTime = new DateTime().toString("yyyy/MM/dd");
             originalFilename = currentDateTime+"/"+originalFilename;

            // 创建PutObjectRequest对象。
//            bucketName   bucket名称
//            ObjectName   上传文件路径+名称
//           inputStream    文件输入流
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucketName, originalFilename, inputStream);
//            设置 该属性可以返回response。如果不设置，则返回的response为空
            putObjectRequest.setProcess("true");

            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
//          返回上传图片在阿里云中的路径
            String url = result.getResponse().getUri();
            return url;
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
